<?php

namespace app\common\traits;

use jianyan\excel\Excel;
use think\facade\Db;
use think\facade\View;
use think\Request;

/**
 * 后台CURD复用
 * Trait Curd
 * @package app\admin\traits
 */
trait Curd
{
    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {

        if (method_exists($this , 'otherData')) {
            $this->otherData($this->request->param() ?? []);
        }
        return view();
    }

    /**
     * 异步获取数据
     * @param Request $request
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View|mixed|\think\response\View
     */
    public function getList()
    {
        if (method_exists($this , 'get_where')) {
            $where = $this->get_where($this->request->param() ?? []);

            $this->model = $this->model->where($where);
        }

        if (method_exists($this , 'get_with')) {
            $with = $this->get_with();
            $this->model = $this->model->with($with);
        }

        $this->request->filter(['strip_tags']);

        $res = $this->model->field($this->field ?? '*')
            ->order($this->order)->paginate($this->request->param('pageSize' , 100));

        // $res = $model->order('id','desc')->paginate($request->param('limit',30));

        $data = [
            'code' => 200 ,
            'msg' => '正在请求中...' ,
            'totalCount' => $res->total() ,
            'data' => $res->items() ,
        ];
        return json($data);
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();

            // 启动事务
            Db::startTrans();
            try {
                $rule = [];
                if (method_exists($this , 'get_check_rule')) {
                    $rule = $this->get_check_rule($post ?? []);
                }
                $this->validate($post , $rule);

                $post['app_id'] = $this->model->getApp();
                $save = $this->model->save($post);

                // 提交事务
                Db::commit();
            } catch ( \Exception $e ) {
                Db::rollback();
                $this->error('保存失败:' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        if (method_exists($this , 'get_other')) {
            $this->get_other($this->request->param() ?? []);
        }
        return view();
    }

    /**
     * 创建/更新之前的操作
     * @param $model
     * @param $request
     * @param string $id ID存在表示更新
     */
    protected function beforeSave($model , $id = '')
    {
        return true;
    }

    /**
     * 添加编辑成功之后要执行的方法
     * @param $request
     * @param $model
     * @param string $id
     */
    protected function afterSave($model , $id = '' , $result)
    {
        return true;
    }

    /**
     * @NodeAnotation(title="编辑/添加")
     */
    public function edit()
    {
        $id = $this->request->param('id');
        $row = $this->model->find($id);

        empty( $row ) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            try {
                $post = $this->request->post();
                $rule = [];
                if (method_exists($this , 'get_check_rule')) {
                    $rule = $this->get_check_rule($post ?? []);
                }
                $this->validate($post , $rule);

                $save = $row->save($post);
            }  catch ( \Exception $e ) {
                $this->error($e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error($e->getMessage());
        }
        View::assign('row' , $row);
        if (method_exists($this , 'get_other')) {
            $this->get_other($this->request->param() ?? []);
        }
        return view('' , compact('row'));
    }

    /**
     * @NodeAnotation(title="编辑/添加")
     */
    public function doEdit(Request $request)
    {

        if ($this->request->isPost()) {

            try {
                // 启动事务
                Db::startTrans();
                $post = $request->except(['create_time','update_time','delete_time']);

                $rule = [];
                if (method_exists($this , 'get_check_rule')) {
                    $rule = $this->get_check_rule($post ?? []);
                }

                $this->validate($post , $rule);
                if (empty(@$post['id'])) { //添加
                    $post['app_id'] = $this->model->getApp();
                    $save = $this->model->save($post);
                } else {//修改

                    $row = $this->model->find($post['id']);
                    $save = $row->save($post);
                }
                Db::commit();
                $data = [
                    'code' => 200 ,
                    'msg' => '修改成功...' ,
                ];
            } catch ( \Exception $e ) {
                Db::rollback();
                $data = [
                    'code' => 202 ,
                    'msg' => $e->getMessage() ,
                ];
            }
            return json($data);
        }
        $id = $this->request->param('id');
        $row = $this->model->find($id);

        View::assign('row' , $row);
        if (method_exists($this , 'get_other')) {
            $this->get_other($this->request->param() ?? []);
        }
        return view('' , compact('row'));
    }

    /**
     * @NodeAnotation(title="删除")
     */
    public function doDelete(Request $request)
    {
        $ids = $request->param('ids');

        is_array($ids) && $row = $this->model->whereIn('id', $ids)->select();
        !is_array($ids) && $row = $this->model->where('id', $ids)->select();
        empty($row) && $this->error('数据不存在');

        try {
            $save = $row->delete();
            $data = [
                'code' => 200 ,
                'msg' => '删除成功...' ,
            ];
        } catch (\Exception $e) {
            $data = [
                'code' => 202 ,
                'msg' =>  '删除失败' ,
                'error' =>$e->getMessage()
            ];
        }
        return json($data);
    }

    /**
     * @NodeAnotation(title="属性修改")
     */
    public function doModify()
    {
        $post = $this->request->param();
        $rule = [
            'id|ID' => 'require' ,
            'field|字段' => 'require' ,
            'value|值' => 'require' ,
        ];
        $this->validate($post , $rule);
        $row = $this->model->find($post['id']);
        if (!$row) {
            $this->error('数据不存在');
        }
        try {
            $row->save([
                $post['field'] => $post['value'] ,
            ]);
            $save = $row->delete();
            $data = [
                'code' => 200 ,
                'msg' => '更新成功...' ,
            ];
        } catch (\Exception $e) {
            $data = [
                'code' => 202 ,
                'msg' =>  '更新失败' ,
                'error' =>$e->getMessage()
            ];
        }
        return json($data);
    }
}